<?php
namespace app\controller;
use \app\model\fileModel;
use \app\model\userModel;
use \core\lib\session;
use \core\view\view;

class userController{
	private $model;
	private $fileModel;
	public function __construct(){
		$this->fileModel = new fileModel();
		$this->model = new userModel();
	}
	public function loginHandler(){
		$username = getvalue("post", "username");
		$password = getvalue("post", "password");
		$ok = $this->model->login($username, $password);
		if($ok){
			jump("/user/collection");
		}else{
			jump("/user/login");
		}
	}
	public function loginJson(){
		$username = getvalue("post", "username");
		$password = getvalue("post", "password");
		$ok = $this->model->login($username, $password);
		echo $ok ? "OK" : "ERROR";
	}
	public function login(){
		view::display("user/login.html");
	}
	public function islogin(){
		//$this->model->login("tisa", "123456");
		$user = session::get("user");
		echo $user ? "OK" : "ERROR";
	}
	public function registerHandler(){
		$username = getvalue("post", "username");
		$password = getvalue("post", "password");
		$ok = $this->model->register($username, $password);
		if($ok){
			jump("/user/collection");
		}else{
			jump("/user/register");
		}
	}
	
	public function logout() {
		session::set("user", false);
		jump("/user/login");
	}
	
	public function register(){
		view::display("user/register.html");
	}
	public function existname(){
		$username = getvalue("username");
		$ok = $this->model->exist($username);
		echo ($ok ? "OK" : "ERROR");
	}
	public function collection(){
		$user = session::get("user");
		if($user == false){
			jump("/user/login");
			exit(0);
		}
		$files = $this->fileModel->loadFileByUser($user['id']);
		$types = $this->fileModel->loadType($user['id']);
		$filesByType = [];
		foreach($types as $type){
			$filesByType[$type['id']] = $this->fileModel->loadFileByType($type['id']);
		}
		view::assign("files", $files);
		view::assign("types", $types);
		view::assign("filesByType", $filesByType);
		view::assign("username", $user['username']);
		view::display("user/collection.html");
	}
	
}
